<?php
if (!defined('_PS_VERSION_'))   
    exit ;

class Vs_CatalogPromotions extends Module 
{
    
    /**
     * Default Constructor
     */  
    public function __construct()
    {
        $this -> name = 'vs_catalogpromotions';
        $this -> tab = 'pricing_promotion';
        $this -> version = '1.0';
        $this -> author = 'Ivan I. Atanasov';
        $this -> need_instance = 0;
        $this -> ps_versions_compliancy = array('min' => '1.4', 'max' => '1.6');
        //$this->dependencies = array('blockcart');

        parent::__construct();

        $this -> displayName = $this -> l('VS Catalog Promotions');
        $this -> description = $this -> l('Automatic Random Promotions on products in your catalog.');

        $this -> confirmUninstall = $this -> l('Are you sure you want to uninstall?');

    }

    /**
     * 
     */
    public function install()
    {
        if (Shop::isFeatureActive())
            Shop::setContext(Shop::CONTEXT_ALL);

        Db::getInstance()->insert('specific_price_rule', array(
                                'name' => 'VSCP',
                                'id_currency'           => 0,
                                'id_country'            => 0,
                                'id_group'              => 0,
                                'from_quantity'         => 1,
                                'price'                 => 0,
                                'reduction'             => 0,
                                'reduction_type'        => 'percentage',
                                'from'                  => date('Y-m-d'),
                                'to'                    => date('Y-m-d', strtotime("+{$countDays} 0"))
                            ));
                            
        $insertId = (int)Db::getInstance()->Insert_ID();
        return parent::install() &&
                $this->registerHook('top') &&
                Configuration::updateValue('VSCP_RULE_ID', $insertId) &&
                Configuration::updateValue('VSCP_COUNT_PRODUCTS', 0) &&
                Configuration::updateValue('VSCP_COUNT_DAYS', 0) &&
                Configuration::updateValue('VSCP_DISCOUNT', 0);
    }

    public function uninstall()
    {
        $ruleId = Configuration::get('VSCP_RULE_ID');
        if($ruleId) {
            Db::getInstance()->delete('specific_price', 'id_specific_price_rule = ' . $ruleId);
            Db::getInstance()->delete('specific_price_rule', 'id_specific_price_rule = ' . $ruleId);
        }
        
        return parent::uninstall() && 
                Configuration::deleteByName('VSCP_RULE_ID') &&
                Configuration::deleteByName('VSCP_COUNT_PRODUCTS') &&
                Configuration::deleteByName('VSCP_COUNT_DAYS') &&
                Configuration::deleteByName('VSCP_DISCOUNT');
    }

    function hookTop($params)
    {
        $ruleId = Configuration::get('VSCP_RULE_ID');
        if(!(int)$ruleId) 
            return;
        
        $row = Db::getInstance()->getRow("SELECT * FROM specific_price_rule WHERE id_specific_price_rule=" . $ruleId);
        if($row && ( strtotime($row['to']) < time() )) {
            $this->_setPriceRules();
        }
    }

    public function getContent()
    {
        $output = null;

        if (Tools::isSubmit('submit'.$this->name)) {
            $countProducts = Tools::getValue('VSCP_COUNT_PRODUCTS');
            $countDays = Tools::getValue('VSCP_COUNT_DAYS');
            $discount = Tools::getValue('VSCP_DISCOUNT');

            Configuration::updateValue('VSCP_COUNT_PRODUCTS', $countProducts);
            Configuration::updateValue('VSCP_COUNT_DAYS', $countDays);
            Configuration::updateValue('VSCP_DISCOUNT', $discount);
            
            $this->_setPriceRules();
            
            $output .= $this->displayConfirmation($this->l('Settings updated'));
        }

        return $output.$this->_displayForm();
    }

    private function _displayForm()
    {
        // Get default Language
        $default_lang = (int)Configuration::get('PS_LANG_DEFAULT');
     
        // Init Fields form array
        $fields_form[0]['form'] = array(
                'legend' => array(
                    'title' => $this->l('Settings'),
                ),
                'input' => array(
                    array(
                        'type' => 'text',
                        'label' => $this->l('Products Count'),
                        'name' => 'VSCP_COUNT_PRODUCTS',
                        'size' => 8,
                        'required' => true
                    ),
                    array(
                        'type' => 'text',
                        'label' => $this->l('Days Count'),
                        'name' => 'VSCP_COUNT_DAYS',
                        'size' => 8,
                        'required' => true
                    ),
                    array(
                        'type' => 'text',
                        'label' => $this->l('Discount'),
                        'name' => 'VSCP_DISCOUNT',
                        'size' => 8,
                        'required' => true
                    ),
                ),
               
                'submit' => array(
                    'title' => $this->l('Save'),
                    'class' => 'button'
                )
            );
     
        $helper = new HelperForm();
         
        // Module, t    oken and currentIndex
        $helper->module = $this;
        $helper->name_controller = $this->name;
        $helper->token = Tools::getAdminTokenLite('AdminModules');
        $helper->currentIndex = AdminController::$currentIndex.'&configure='.$this->name;
     
        // Language
        $helper->default_form_language = $default_lang;
        $helper->allow_employee_form_lang = $default_lang;
     
        // Title and toolbar
        $helper->title = $this->displayName;
        $helper->show_toolbar = true;        // false -> remove toolbar
        $helper->toolbar_scroll = true;      // yes - > Toolbar is always visible on the top of the screen.
        $helper->submit_action = 'submit'.$this->name;
        $helper->toolbar_btn = array(
            'save' =>
                array(
                    'desc' => $this->l('Save'),
                    'href' => AdminController::$currentIndex.'&configure='.$this->name.'&save'.$this->name.
                    '&token='.Tools::getAdminTokenLite('AdminModules'),
                ),
                'back' => array(
                    'href' => AdminController::$currentIndex.'&token='.Tools::getAdminTokenLite('AdminModules'),
                    'desc' => $this->l('Back to list')
                )
            );
        // Load current values
        $helper->fields_value['VSCP_COUNT_PRODUCTS'] = Configuration::get('VSCP_COUNT_PRODUCTS');
        $helper->fields_value['VSCP_COUNT_DAYS'] = Configuration::get('VSCP_COUNT_DAYS');
        $helper->fields_value['VSCP_DISCOUNT'] = Configuration::get('VSCP_DISCOUNT');
     
        return $helper->generateForm($fields_form);
    }

    private function _setPriceRules()
    {
        $ruleId = Configuration::get('VSCP_RULE_ID');
        $countProducts = Configuration::get('VSCP_COUNT_PRODUCTS');
        $countDays = Configuration::get('VSCP_COUNT_DAYS');
        $discount = Configuration::get('VSCP_DISCOUNT');
        //die(var_dump($ruleId));
        if(!(int)$ruleId) {
            throw new Exception("VS Catalog Promotions Rule ID is not set.");
        }
        
        Db::getInstance()->delete('specific_price', 'id_specific_price_rule = ' . $ruleId);
        if ($results = Db::getInstance()->ExecuteS('SELECT * FROM ps_product ORDER BY RAND() LIMIT ' . $countProducts)) {
            foreach ($results as $row) {
                Db::getInstance()->insert('specific_price', array(
                                'id_specific_price_rule' => (int)$ruleId,
                                'id_product'      => $row['id_product'],
                                'price'                 => -1.0,
                                'from_quantity'         => 1,
                                'reduction'             => $discount / 100,
                                'reduction_type'        => 'percentage',
                                'from'                  => date('Y-m-d'),
                                'to'                    => date('Y-m-d', strtotime("+{$countDays} days"))
                            ));
                
                if(Db::getInstance()->getNumberError()) {
                    die(Db::getInstance()->getMsgError());
                }
            }
        }
    }
}
        